package net.chenlin.dp.ids.server.controller;

import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.CacheConst;
import net.chenlin.dp.ids.common.constant.GlobalErrorEnum;
import net.chenlin.dp.ids.common.constant.IdsConst;
import net.chenlin.dp.ids.common.entity.SessionData;
import net.chenlin.dp.ids.common.entity.TicketValidateResultDTO;
import net.chenlin.dp.ids.common.util.CommonUtil;
import net.chenlin.dp.ids.server.entity.IdsUserEntity;
import net.chenlin.dp.ids.server.manager.ConfigManager;
import net.chenlin.dp.ids.server.manager.LoginManager;
import net.chenlin.dp.ids.server.service.IdsUserService;
import net.chenlin.dp.ids.server.util.EncryptUtil;
import net.chenlin.dp.ids.server.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * ids app controller
 * @author zcl<yczclcn@163.com>
 */
@RestController
@RequestMapping("/app")
public class IdsAppController {

    @Autowired
    private IdsUserService userService;

    @Autowired
    private LoginManager loginManager;

    @Autowired
    private ConfigManager configManager;

    /**
     * app登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(IdsConst.LOGIN_URL)
    public BaseResult login(String username, String password) {
        if (CommonUtil.strIsEmpty(username.trim())) {
            return GlobalErrorEnum.USERNAME_NOT_NULL.getResult();
        }
        if (CommonUtil.strIsEmpty(password.trim())) {
            return GlobalErrorEnum.PASSWORD_NOT_NULL.getResult();
        }
        IdsUserEntity userEntity = userService.getByUserName(username);
        if (userEntity == null) {
            return GlobalErrorEnum.USERNAME_ERROR.getResult();
        }
        String checkPassword;
        try {
            checkPassword = IdUtil.md5(EncryptUtil.decryptByPrivateKey(password,
                    configManager.getConfig(CacheConst.PRIVATE_KEY)), userEntity.getSalt());
        } catch (Exception e) {
            // 密码解密异常
            return GlobalErrorEnum.ERROR.getResult();
        }
        if (!userEntity.getPassword().equals(checkPassword)) {
            return GlobalErrorEnum.PASSWORD_ERROR.getResult();
        }
        if (userEntity.getStatus() == 0) {
            return GlobalErrorEnum.ACCOUNT_LOCKED.getResult();
        }
        // 登录成功
        SessionData sessionData = new SessionData(userEntity.getId(), userEntity.getUsername(),
                userEntity.getStatus(), IdsConst.LOGIN_TYPE_APP);
        sessionData.setIsLogin(1);
        // app登录默认记住登录7天
        sessionData.setRememberMe(true);
        Map<String, String> token = loginManager.login(sessionData);
        BaseResult baseResult = GlobalErrorEnum.SUCCESS.getResult();
        baseResult.setRespData(token);
        return baseResult;
    }

    /**
     * ticket校验
     * @param ticket
     * @return
     */
    @RequestMapping(IdsConst.AUTH_URL)
    public BaseResult auth(String ticket) {
        if (CommonUtil.strIsEmpty(ticket)) {
            return GlobalErrorEnum.USERNAME_NOT_NULL.getResult();
        }
        TicketValidateResultDTO validateResultDTO = loginManager.ticketCheck(ticket);
        if (validateResultDTO != null) {
            Map<String, Object> authMap = new HashMap<>(1);
            authMap.put(IdsConst.TOKEN_PARAM_KEY, validateResultDTO.getSessionId());
            return GlobalErrorEnum.SUCCESS.getResult().setRespData(authMap);
        }
        return GlobalErrorEnum.NOT_LOGIN.getResult();
    }

    /**
     * app登出
     * @param token
     * @return
     */
    @RequestMapping(IdsConst.LOGOUT_URL)
    public BaseResult logout(String token) {
        if (CommonUtil.strIsEmpty(token.trim())) {
            return GlobalErrorEnum.BizError.getResult().setRespMsg("sessionId为空");
        }
        loginManager.logout(token);
        return GlobalErrorEnum.SUCCESS.getResult();
    }

    /**
     * app登录状态校验
     * @param token
     * @return
     */
    @RequestMapping(IdsConst.AUTH_STATUS_URL)
    public BaseResult authStatus(String token) {
        if (CommonUtil.strIsEmpty(token.trim())) {
            return GlobalErrorEnum.BizError.getResult().setRespMsg("sessionId为空");
        }
        SessionData sessionData = loginManager.loginCheck(token);
        if (sessionData == null) {
            return GlobalErrorEnum.NOT_LOGIN.getResult();
        }
        return GlobalErrorEnum.HAS_LOGIN.getResult();
    }

}
